#include "stdafx.h"
#include "Parser.h"

#include "Commands.h"

#include "StateOfTheWorld.h"


CParser::CParser(void)
{
}

bool CParser::CheckExpression(std::string & expression, std::vector<std::string> & commands)
{
	if (expression == "")
		return false;

	if ((CheckCommand(expression.substr(0, int(expression.length()) - 1))) && (expression[int(expression.length()) - 1] == ';'))
	{
		expression = expression.substr(0, expression.length() - 1);
		commands.push_back(expression);
		return true;
	}
	else
	{
		return SearchWhileConstruction(expression, commands);
	}
}

bool CParser::CheckCommand(std::string & command)
{
	return  (command == ATTACK || command == BACKWARD || command == FORWARD ||
			 command == GO || command == LEFT || command == RIGHT || command == SAY ||
			 command == STOP || command == WORK);
}

bool CParser::SearchWhileConstruction(std::string & expression, std::vector<std::string> & commands)
{
	if (expression.find(" ") != std::string::npos)
	{
		unsigned int index = expression.find(" ");
		std::string firstCommand = expression.substr(0, index);
		
		if (firstCommand != "while")
			return false;
	
		expression = expression.substr(index + 1, int(expression.length()) - 6);
		if (expression[0] != '(')
			return false;

		std::string condition;
		std::string command;

		if (expression.find("(") != std::string::npos &&
			expression.find(")") != std::string::npos)
		{
			int pos1, pos2;
			pos1 = expression.find("(");
			//pos2 = expression.find(")");
			if (expression.substr(pos1 + 1, DAY.length()) == DAY || expression.substr(pos1 + 1, NIGHT.length()) == NIGHT)
			{
				std::string s = expression.substr(pos1 + 1, DAY.length());
				(expression.substr(pos1 + 1, DAY.length()) == DAY)
					? condition = DAY
					: condition = NIGHT;
			}
			else
				return false;
		}
		else
			return false;

		if (expression.find(" ") != std::string::npos)
		{
			index = expression.find(" ");
			command = expression.substr((index + 1), (int(expression.length()) - 1 - index));
			
			if (!((CheckCommand(command.substr(0, int(command.length()) - 1))) && (command[int(command.length()) - 1] == ';')))
				return false;

			command = command.substr(0, command.length() - 1);
		}
		else
			return false;

		commands.push_back(firstCommand);
		commands.push_back(condition);
		commands.push_back(command);

		return true;
	}
	else
	{
		return false;
	}
}
